import { Injectable } from '@angular/core';
import { AlertController } from '@ionic/angular';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpStatusCode } from '@angular/common/http';

import { catchError } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';

import { pb } from 'src/pb';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(
    private alertCtrl: AlertController,
  ) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req)
      .pipe(
        catchError((err: HttpErrorResponse) => {
          switch (err.status) {
            case HttpStatusCode.InternalServerError:
              const msg = pb.Error.decode(new Uint8Array(err.error as ArrayBuffer));
              this.alert(msg.error);

              break;
            default:
              console.error(
                `Backend returned code ${err.status}, ` +
                `body was: ${err.error}`);
          }

          return throwError('网络数据获取异常.');
        }));
  }

  private async alert(err: string) {
    const alert = await this.alertCtrl.create({
      header: '异常',
      message: err,
      buttons: ['关闭']
    });

    await alert.present();
  }
}
